/**
* by yaojiewei
* 重写axios方法
**/
import axios from 'axios'
import qs from 'qs'
import router from '../main';
import env from '../config/env';

const ajaxUrl = env === 'development'
    ? 'api'
    : env === 'production'
        ? 'https://www.url.com'
        : 'https://debug.url.com';

axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = ajaxUrl;
//POST传参序列化
axios.interceptors.request.use((config) => {
  if(config.method  === 'post'){
    config.data = qs.stringify(config.data);
  }
  // if (window.localStorage.getItem('token')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
  //   config.headers.token = window.localStorage.getItem('token');
  //   config.headers.Cookie = window.localStorage.getItem('token');
  // }
  // console.log(JSON.stringify(config));
  return config;
},(error) =>{
  console.log("错误的传参");
  return Promise.reject(error);
});

//code状态码200判断
axios.interceptors.response.use((res) =>{
  return res;
}, (error) => {
  console.log("网络异常");
  console.log(error);
  if (error.response) {
    switch (error.response.status) {
      case 401:
        router.replace({
          path: '/login',
          params: {redirect: router.currentRoute.name}
        })
    }
  }
  return Promise.reject(error);
});

export default axios;
